// pages/shoppingCart/shoppingCart.js
const app = getApp()
import Api from '../../utils/api';
import util from '../../utils/util';
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    isLogin: false, //是否登录标记
    cartShopList: [], //购物车店铺列表
    isShopSelect: false, //选中状态
    isShowIcon: true,
    shopindex: 0, //付款的时候 需要的索引值
    goodsindex: 0,
    shoppingDataLength: 0, //购物车数量
    finalMoney: 0, //合计
    istemplate: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let _this = this;
    this.isProductRelease();
    let thirdSession = wx.getStorageSync('third_Session');
    this.setData({
      isLogin: thirdSession
    })
    if (thirdSession) {
      //已登录
      console.log('已登录');
      _this.queryCart();
    }else{
      console.log('未登录');
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    app.globalData.otherPageHideFlag = true;
  },
  //去购物
  toShopping(){
    //获取最近浏览的店铺
    Api.lastAddCartShop().then(res=>{
      console.log('最近一次添加购物车店铺',res);
      if(res.data){
        wx.navigateTo({
          url: `/pages/shopClass/shopClass?id=${res.data.id}`,
        })
      }else{
        wx.switchTab({
          url: '/pages/sort/sort',
        })
      }
    });
  },
  //去登陆
  toLogin(){
    wx.navigateTo({
      url: '/pages/logs/logs',
    })
  },
  //查询购物车
  queryCart() {
    let _this = this;
    Api.queryCart().then(res => {
      console.log(res)
      let list = res.data;
      //let ss = JSON.parse(JSON.stringify(res.data[0]));
      //list.push(ss)
      list.forEach(function(item, index, arr) {
        item.isShopSelect = false;
        item.isShopIcon = true;
        item.cartItemList.forEach(function(t, i, a) {
          t.isGoodsSelect = false;
          t.isGoodsIcon = true;
        });
      });
      _this.setData({
        cartShopList: list,
      });
      app.loadCartNum();
    })
  },

  //删除购物车
  delGoods(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let goodsindex = e.currentTarget.dataset.goodsindex;
    let id = _this.data.cartShopList[shopindex].cartItemList[goodsindex].id;
    let data = {
      ids: id
    }
    Api.delGoods(data).then(res => {
      console.log("删除购物车", res)
      if(res.flag){
      let arr = _this.data.cartShopList;
      if (arr[shopindex].cartItemList.length == 1) {
        arr.splice(shopindex, 1);
      } else {
        arr[shopindex].cartItemList.splice(goodsindex, 1);
      }
      _this.setData({
        cartShopList: arr
      });
        wx.showToast({
          title: '删除成功',
          icon: 'none'
        })
      _this.finalMoney();
      app.loadCartNum();
      }
    });

  },

  //店铺全选
  shopAllSelect(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let arr = _this.data.cartShopList;

    if (arr[shopindex].isShopSelect) { //已经是全选中状态
      //arr[shopindex].isShopSelect = false;
      //console.log(111)
      _this.shopSelect(arr);
    } else { //
      //arr[shopindex].isShopSelect = true;
      _this.shopAllData(arr, shopindex);
    }
    _this.finalMoney();
  },

  //点击店铺的全选按钮操作列表数据
  shopAllData(arr, shopindex, isIcon) { //当前操作的店铺索引
    let _this = this;
    arr.forEach(function(item, index, r) {
      if (index == shopindex) {
        item.isShopSelect = true;
        item.isShopIcon = true;
        item.cartItemList.forEach(function(t, i, a) {
          t.isGoodsSelect = true;
          t.isGoodsIcon = true;
        });
      } else {
        item.isShopSelect = false;
        item.isShopIcon = false;
        item.cartItemList.forEach(function(t, i, a) {
          t.isGoodsSelect = false;
          t.isGoodsIcon = false;
        });
      }
    });
    _this.setData({
      cartShopList: arr,
      shopindex: shopindex,
    });
  },

  //所有店铺里没有选中的商品  会重新打开全部店铺选择环境  相当于初始化
  shopSelect(arr) {
    let _this = this;
    arr.forEach(function(item, index, r) {
      item.isShopSelect = false;
      item.isShopIcon = true;
      item.cartItemList.forEach(function(t, i, a) {
        t.isGoodsSelect = false;
        t.isGoodsIcon = true;
      });
    });
    _this.setData({
      cartShopList: arr,
    });
  },

  //点击店铺商品分类
  goodsSelect(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let goodsindex = e.currentTarget.dataset.goodsindex;
    let arr = _this.data.cartShopList;
    //console.log(shopindex, goodsindex)


    if (arr[shopindex].cartItemList[goodsindex].isGoodsSelect) {
      //console.log(111)
      arr[shopindex].cartItemList[goodsindex].isGoodsSelect = false;
      //判断当前店铺是否还有选中的商品
      let flag = arr[shopindex].cartItemList.filter(function(item, index, arr) {
        return item.isGoodsSelect
      })
      if (flag.length <= 0) {
        _this.shopSelect(arr);
      } else {
        arr[shopindex].isShopSelect = false;
      }
      //console.log(flag)
    } else {
      arr.forEach(function(item, index, r) {
        if (index == shopindex) {
          item.isShopIcon = true;
          item.cartItemList.forEach(function(t, i, a) {
            if (i == goodsindex) {
              t.isGoodsSelect = true;
            }
            t.isGoodsIcon = true;
          });
          //判断所有商品是否全部选中状态
          let flag = arr[shopindex].cartItemList.filter(function(item, index, arr) {
            return !item.isGoodsSelect
          })
          //console.log(flag)
          if (flag.length <= 0) {
            item.isShopSelect = true;
          }
        } else {
          item.isShopSelect = false;
          item.isShopIcon = false;
          item.cartItemList.forEach(function(t, i, a) {
            t.isGoodsSelect = false;
            t.isGoodsIcon = false;
          });
        }
      });

    }
    _this.setData({
      cartShopList: arr,
      shopindex: shopindex,
      goodsindex: goodsindex,
    })
    _this.finalMoney();
  },

  //去订单页面
  goOrder() {
    let _this = this;
    let cartItemDtoList = []; //选中的购物车列表
    let cartShopList = _this.data.cartShopList;
    let shopId = '';
    cartShopList.forEach(function(item, index, arr) {
      if (item.isShopSelect) {
        shopId = item.shopId
        item.cartItemList.forEach(function(t, i, r) {
          t.cartItemId = t.id
          t.defaultImage = t.image;
        })
        cartItemDtoList = item.cartItemList;
      } else {
        item.cartItemList.forEach(function(t, i, r) {
          if (t.isGoodsSelect) {
            // console.log("店铺：", index);
            // console.log("商品：", i);
            shopId = item.shopId;
            t.cartItemId = t.id;
            t.defaultImage = t.image;
            cartItemDtoList.push(t);
          }
        })
      }
    })
    console.log(cartItemDtoList)
    if (cartItemDtoList.length < 1) { //没有选择商品
      return false
    }
    wx.setStorageSync('cartItemDtoList', cartItemDtoList)
    wx.navigateTo({
      url: `/pages/order/order?shopId=${shopId}`,
    })
  },

  //减法
  reduceClick(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let goodsindex = e.currentTarget.dataset.goodsindex;
    let arr = _this.data.cartShopList;
    console.log(_this.data.cartShopList[shopindex])
    if (arr[shopindex].cartItemList[goodsindex].num <= 1) {
      arr[shopindex].cartItemList[goodsindex].num = 1
      _this.setData({
        cartShopList: arr
      })
      return;
    }
    arr[shopindex].cartItemList[goodsindex].num--;
    _this.setData({
      cartShopList: arr
    })
    _this.addCart(arr[shopindex].cartItemList[goodsindex].goodsId, -1, goodsindex, shopindex);
    //this.finalMoney();
  },

  //加法
  addClick(e) {
    let _this = this;
    let shopindex = e.currentTarget.dataset.shopindex;
    let goodsindex = e.currentTarget.dataset.goodsindex;

    let arr = _this.data.cartShopList;
    //console.log(arr[shopindex])
    arr[shopindex].cartItemList[goodsindex].num++;
    _this.setData({
      cartShopList: arr
    })
    _this.addCart(arr[shopindex].cartItemList[goodsindex].goodsId, 1, goodsindex, shopindex);
    //_this.finalMoney();
  },


  //计算总价格
  finalMoney() {
    let _this = this;
    let arr = _this.data.cartShopList;
    let finalMoney = 0
    arr.forEach(function(item, index, arr) {
      if (item.isShopIcon) {
        item.cartItemList.forEach(function(t, i, r) {
          if (t.isGoodsSelect) {
            finalMoney += t.totalPrice
          }
        })
      }
    })
    //console.log(finalMoney)
    _this.setData({
      finalMoney: finalMoney.toFixed(2)
    })
  },
  //跳转商品详情
  intoGoodsDesc(e) {
    let goodsId = e.currentTarget.dataset.goodsindex;
    console.log('跳转店铺详情', goodsId);
    wx.navigateTo({
      url: `/pages/details/shopDetail?id=${goodsId}`,
    })
  },

  //添加购物车
  addCart(id, num, goodsindex, shopindex) {
    let _this = this;
    console.log(num)
    Api.addCart(id, num, goodsindex, shopindex).then(res => {
      //console.log("添加购物车",res)
      let arr = _this.data.cartShopList;
      //arr[shopindex].cartItemList[goodsindex].num = res.data[0].cartItemList[0].num
      arr[shopindex].cartItemList[goodsindex].totalPrice = res.data[0].cartItemList[0].totalPrice
      _this.setData({
        cartShopList: arr
      })
      _this.finalMoney();
    })
  },
  //判断产品发布信息
  isProductRelease() {
    let _this = this;
    Api.isProductRelease().then(res => {
      console.log('进入标记查询', res)
      _this.setData({
        istemplate: res.data
      })
    }).catch(err => {
      _this.setData({
        istemplate: true
      })
    });
  }

})